﻿using System;
using System.Windows;
using DL.PhotoCollage.Core;

namespace DL.PhotoCollage.Wpf.Presentation
{
    public abstract class ControllerBase
    {
        private readonly object threadLock = new object();

        private readonly Random random;       

        protected ControllerBase(string applicationLocalDataDirectory)
        {
            this.random = new Random();
            this.LocalDataDirectory = applicationLocalDataDirectory;
        }

        public ScreensaverConfiguration Configuration { get; private set; }

        public IConfigurationRepository ConfigurationRepository { get; protected set; }

        protected Application Application { get; set; }       

        protected string LocalDataDirectory { get; private set; }

        public void HandleError(Exception exception, bool showMessage = false)
        {
            this.LogErrorMessage(exception);

            if (showMessage)
            {
                this.DisplayErrorMessage(exception.Message);
            }
        }

        public void DisplayErrorMessage(string message)
        {
            MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        public int GetRandomNumber(int min, int max)
        {
            int value;

            lock (threadLock)
            {
                value = this.random.Next(min, max);
            }

            return value;
        }

        public abstract void StartApplication();

        public void ShutdownApplication()
        {
            this.Application.Shutdown();
        }

        protected void LoadConfigurationSettings()
        {
            this.Configuration = this.ConfigurationRepository.Load();
        }

        private ILogger GetLogger()
        {
            return new TextLogger(this.LocalDataDirectory);
        }

        private void LogErrorMessage(Exception exception)
        {
            ILogger logger = this.GetLogger();

            if (this.Configuration.UseVerboseLogging)
            {
                logger.Log(exception.Message, exception.StackTrace);
            }
            else
            {
                logger.Log(exception.Message);
            }
        }   
    }
}
